import type { NotifyOptions } from './types'
import NotifyContainer from './NotifyContainer.vue'
import { exposedOf, renderInBody } from '../util'
import type { MessageType } from '../message/types'

interface NotifyInstance {
  destroy(): void
}

function destroy(key: string) {
  exposedOf<InstanceType<typeof NotifyContainer>>(vNode, (e) => {
    e.destroy(key)
  })
}

function create(opts: NotifyOptions, type?: MessageType): NotifyInstance {
  return exposedOf<InstanceType<typeof NotifyContainer>>(vNode, (e) => {
    const key = e.create(opts, type)
    return {
      destroy() {
        destroy(key)
      }
    }
  })!
}

export const notify = {
  notify(opts: NotifyOptions): NotifyInstance {
    return create(opts)
  },
  info(opts: NotifyOptions): NotifyInstance {
    return create(opts, 'info')
  },
  success(opts: NotifyOptions): NotifyInstance {
    return create(opts, 'success')
  },
  warn(opts: NotifyOptions): NotifyInstance {
    return create(opts, 'warn')
  },
  error(opts: NotifyOptions): NotifyInstance {
    return create(opts, 'error')
  }
}

const vNode = renderInBody(NotifyContainer)
